import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_learn_vi/src/bean/bean_AppHomeEntity.dart';
import 'package:flutter_learn_vi/src/bean/bean_common_config.dart';
import 'package:flutter_learn_vi/src/bean/bean_global.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/common/global.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/model/user_model.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/home/new/v2_home_item_study_widget.dart';
import 'package:flutter_learn_vi/src/page/home/new/v4_home_item_bottom_list_widget.dart';
import 'package:flutter_learn_vi/src/page/home/new/v4_home_item_study_widget.dart';
import 'package:flutter_learn_vi/src/page/news/news_detaile_page.dart';
import 'package:flutter_learn_vi/src/page/study/course/course_video_detail_page.dart';
import 'package:flutter_learn_vi/src/page/study/main_video_v2_page.dart';
import 'package:flutter_learn_vi/src/page/train/approve/train_aprove_widget.dart';
import 'package:flutter_learn_vi/src/page/train/tain_main_page.dart';
import 'package:flutter_learn_vi/src/page/train/train_list_details_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/string_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

import '../model_home.dart';
import 'kuang_home_number_widget.dart';

//lib/src/page/home/home_item_page.dart
//首页面显示的视频列表播放页面
//首页面显示的视频列表播放页面
class HomeItemMainV4Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeItemMainV4PageState();
  }
}

class _HomeItemMainV4PageState extends State
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      vsync: this,
      length: 3,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(
              top: MediaQueryData.fromWindow(window).padding.top),
          child: TabBar(
            labelColor: Colors.black,
            unselectedLabelColor: Colors.black,
            labelStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
            indicatorColor: Colors.green,
            unselectedLabelStyle: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w400,
            ),
            isScrollable: true,
            tabs: [
              Tab(
                text: "精选",
              ),
              Tab(
                text: "在线学习",
              ),
              Tab(
                text: "我的培训",
              ),
            ],
            controller: _tabController,
          ),
        ),
        Expanded(
          child: Container(
            child: TabBarView(
              controller: _tabController,
              children: [
                HomeItemMainV4ItemPage(),
                VideoStudyMainV2Page(
                  pageIndex: 0,
                ),
                TrainMainPage(
                  pageIndex: 1,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

class HomeItemMainV4ItemPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeItemMainV4ItemPageState();
  }
}

//使用到[TabBar] 所以要绑定一个Ticker
//当前页面被装载在[PageView]中，使用KeepAlive使用页面保持状态
class _HomeItemMainV4ItemPageState extends State
    with
        AutomaticKeepAliveClientMixin,
        SingleTickerProviderStateMixin,
        UserModel,
        HomeModel {
  //页面保持状态
  @override
  bool get wantKeepAlive => true;

  //页面初始化方法
  @override
  void initState() {
    super.initState();
    rootStreamController.stream.listen((event) {
      if (event.code == 204) {
        isStudyModel = event.data;
        Future.delayed(Duration.zero, () {
          setState(() {});
        });
      }
    });

    _getNewsList();
  }

  //页面销毁回调生命周期
  @override
  void dispose() {
    super.dispose();
  }

  List<BeanAppHomeEntity> _bannerList = [];

  //有领导信箱的内容
  double _defaultHeader = 290;

  ///是否加载学习版块
  bool isStudyModel = false;

  //无
  double _defaultHeader2 = 230;

  Future<bool> _getNewsList() async {
    // ResponseInfo responseBannerInfo = await DioUtils.instance.getRequest(
    //   url: HttpHelper.home_banner_url,
    // );
    // if (responseBannerInfo.success) {
    //   List list = responseBannerInfo.data;
    //
    //   _bannerListgetNewsList = [];
    //   list.forEach((element) {
    //     BannerBean newsBean = BannerBean.fromJson(element);
    //     _bannerList.add(newsBean);
    //   });
    // }
    _bannerList = await getHomeList(isBanner: 1);

    ResponseInfo integralResponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.commonConfigUrl,
    );
    if (integralResponseInfo.success) {
      List list = integralResponseInfo.data;
      List<CommonConfigBean> configList = [];
      if (list != null && list.length > 0) {
        list.forEach((element) {
          CommonConfigBean commonConfigBean = CommonConfigBean.fromMap(element);
          configList.add(commonConfigBean);
        });
      }
      UserHelper.getInstance.configList = configList;
    }

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }

  ///代码清单 5-19 NestedScrollView 下拉刷新
  ///lib/code/code5/example_504_CustomScrollView.dart
  @override
  Widget build(BuildContext context) {
    super.build(context);
    //构建页面的主体
    return Scaffold(
      //下拉刷新
      body: RefreshIndicator(
        //可滚动组件在滚动时会发送ScrollNotification类型的通知
        notificationPredicate: (ScrollNotification notifation) {
          //该属性包含当前ViewPort及滚动位置等信息
          ScrollMetrics scrollMetrics = notifation.metrics;
          if (scrollMetrics.minScrollExtent == 0) {
            return true;
          } else {
            return false;
          }
        },
        //下拉刷新回调方法
        onRefresh: () async {
          //模拟网络刷新 等待2秒
          await getUserInfo();
          await _getNewsList();
          rootStreamController.add(GlobalBean(203, null));
          ToastUtils.showToast("已刷新");
          //返回值以结束刷新
          return Future.value(true);
        },
        child: buildNestedScrollView(),
      ),
    );
  }

  ///代码清单 5-20 NestedScrollView 的创建
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildNestedScrollView() {
    if (UserHelper.getInstance.userBean == null) {
      return Container();
    }

    //滑动视图
    return NestedScrollView(
      //配置可折叠的头布局
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          SliverToBoxAdapter(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                buildBannerWidget(),
                HomeitemStudyV4Widget(),
                Row(
                  children: [
                    EailsNumberWidget(),
                    TrainApproveWidget(),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(left: 12, top: 16),
                  child: Text(
                    "最新动态",
                    style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 18,
                    ),
                  ),
                )
              ],
            ),
          )
        ];
      },
      //页面的主体内容
      body: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(8),
          ),
        ),
        margin: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 0),
        padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 20),
        child: HomeItemBottomListWidget(),
      ),
    );
  }

  ///代码清单 5-24 FlexibleSpaceBar 中的内容
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildFlexibleSpaceWidget() {
    //上下排列的线性布局
    return Container(
      color: Colors.grey[200],
      child: Stack(
        children: [
          //第一部分是一个 轮播图
          Container(
            height: 270,
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
          ),
          Positioned(
            left: 0,
            top: 83,
            right: 0,
            child: Column(
              children: [
                //第二部分是左右排列的两个图标
                buildBannerWidget(),
                HomeitemStudyV2Widget(),
              ],
            ),
          )
        ],
      ),
    );
  }

  ///代码清单 5-25 FlexibleSpaceBar 中的内容
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildBannerWidget() {
    return Container(
        color: Colors.white,
        height: 220,
        padding: EdgeInsets.only(bottom: 10, top: 8),
        child: _bannerList.length == 0
            ? NoDataWidget(
                clickCallBack: () {
                  _getNewsList();
                },
              )
            : Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    child: buildCachedNetworkImage(index),
                  );
                },
                onTap: (int index) {
                  BeanAppHomeEntity bean = _bannerList[index];

                  /// 1 资讯 ，2 视频， 3 培训 , 4 考试
                  int bannerType = bean.listType;
                  NavigatorUtils.pushPage(
                    context,
                    buildDetailPage(bean),
                  );
                },
                loop: true,
                autoplay: true,
                duration: 500,
                viewportFraction: 0.9,
                autoplayDelay: 10000,
                scale: 0.9,
                itemCount: _bannerList.length,
                pagination: new SwiperPagination(),
              ));
  }

  Widget buildCachedNetworkImage(int index) {
    BeanAppHomeEntity entity = _bannerList[index];
    if (StringUtils.isEmpty(entity.image)) {
      String path = "assets/images/2.0x/train_icon.png";
      String flag = "";
      if (entity.listType == 2) {
        flag = "视频学习";
        path = "assets/images/2.0x/video_icon.png";
      } else if (entity.listType == 3) {
        path = "assets/images/2.0x/train_icon.png";
        flag = "培训学习";
      }
      return Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.blueGrey.withOpacity(0.2),
          borderRadius: BorderRadius.all(Radius.circular(4)),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  path,
                  width: 33,
                ),
                SizedBox(
                  width: 12,
                ),
                Text("$flag")
              ],
            ),
            SizedBox(
              height: 12,
            ),
            Text("${entity.title}")
          ],
        ),
      );
    }
    return CachedNetworkImage(
      fit: BoxFit.fill,
      imageUrl: entity.image,
    );
  }

  Widget buildDetailPage(BeanAppHomeEntity bean) {
    Widget flag;
    switch (bean.listType) {
      case 1:
        flag = NewsDetailePage(
          newsId: bean.id,
          screenSize: MediaQuery.of(context).size,
        );
        break;
      case 2:
        flag = CourseVideoDetailsPage(
          videoCourseId: bean.id2,
          videoId: bean.id,
        );
        break;
      case 3:
        flag = TrainListDetailsPage(
          approveBean: TrainApproveBean(
            bean.id,
            bean.createTime,
            examId: bean.id2,
          ),
        );
        break;
      case 4:
        break;
    }
    return flag;
  }

  Expanded buildHeaderClass(
      {@required String image, @required String text, Function onTap}) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          height: 60,
          decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.4),
              borderRadius: BorderRadius.all(Radius.circular(4))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                image,
                fit: BoxFit.fill,
                width: 38,
                height: 38,
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                text,
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
